﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
//添加命名空间

namespace TheEnd
{
    public partial class FormChild : Form
    {

        BindingList<string> notifyData = new BindingList<string>();

        public FormChild()
        {
            InitializeComponent();
            IDataObject iData = Clipboard.GetDataObject();

        }
        //加粗按钮部分
        public void toolStripButtonBold_Click(object sender, EventArgs e)
        {
            //点击按钮加粗，加粗时再次点击取消
            if (textBoxNode.Font.Bold == false)
            {
                textBoxNode.Font = new Font(textBoxNode.Font, FontStyle.Bold);
            }
            else
            {
                textBoxNode.Font = new Font(textBoxNode.Font, FontStyle.Regular);
            }
        }
        //斜体按钮部分
        public void toolStripButtonItalic_Click(object sender, EventArgs e)
        {
            //点击一下倾斜，再次点击取消倾斜字体
            if (textBoxNode.Font.Italic == false)
            {
                textBoxNode.Font = new Font(textBoxNode.Font, FontStyle.Italic);
            }
            else
            {
                textBoxNode.Font = new Font(textBoxNode.Font, FontStyle.Regular);
            }
        }
        //保存文档
        public void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            if (textBoxNode.Text.Trim() != "")
            {
                if (this.Text == "SimpleIDE")
                {
                    //判断用户点击的时保存按钮还是取消按钮
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        //保存文件到用户指定的目录位置
                        //获取用户选择文件和路径
                        string path = saveFileDialog1.FileName;
                        //保存文件到指定位置
                        textBoxNode.SaveFile(path, RichTextBoxStreamType.PlainText);
                        string[] path_list = path.Split('\\');
                        this.Parent.Text = path_list[path_list.Length - 1];
                        this.Text = path;
                    }
                }
                else
                {
                    //保存文件到用户指定的目录位置
                    //获取用户选择文件和路径
                    string path = this.Text;
                    //保存文件到指定位置
                    textBoxNode.SaveFile(path, RichTextBoxStreamType.PlainText);
                }
            }
            else
            {
                MessageBox.Show("空文档不能保存", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            toolStripLabelMake.Text = "";
        }
        //打开文档
        public void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //获取打开文档的路径
                string path = openFileDialog1.FileName;

                //打开文件
                StreamReader sr = new StreamReader(path, Encoding.UTF8);
                textBoxNode.Text = sr.ReadToEnd();
                //textBoxNode.LoadFile(path, RichTextBoxStreamType.PlainText);
                //打开的时候将打开的文件路径写到当前窗体，并且清空记号
                sr.Dispose();
                sr.Close();
                string[] path_list = path.Split('\\');
                this.Parent.Text = path_list[path_list.Length - 1];
                this.Text = path;

                toolStripLabelMake.Text = "";
                //MessageBox.Show(TxtFileEncoder.GetEncoding(path).EncodingName);
            }

        }
        //编辑文本时，内容变化了，让记号变成星号
        private void textBoxNode_TextChanged(object sender, EventArgs e)
        {
            //showLineNo();
            if (textBoxNode.Text.Trim() != "")
            {
                toolStripLabelMake.Text = "*";
            }
            else
            {
                toolStripLabelMake.Text = "";
            }

        }

        private void FormChild_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断记号是否是"*"
            if (toolStripLabelMake.Text == "*")
            {
                //如果是"*",提示用户没有保存
                DialogResult result = MessageBox.Show("文档尚未保存，确定要继续退出吗？", "信息询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    this.Dispose();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void textBoxNode_VScroll(object sender, EventArgs e)
        {
            //showLineNo();
        }
        int oldwidth = 0;
        private void FormChild_Load(object sender, EventArgs e)
        {
            oldwidth = this.Width;
            textBoxNode.KeyDown += new KeyEventHandler(rich_KeyDown);
            textBoxNode.BackColor = Color.FromArgb(52, 61, 70);
            lineNumber.BackColor = Color.FromArgb(52, 61, 70);
            lineNumber.ForeColor = Color.FromArgb(134, 142, 152);
            notifyBox.Width = 150;
            notifyBox.Height = textBoxNode.Font.Height;
            notifyBox.DataSource = notifyData;
            foreach(string s in AllClass().Keys)
            {
                notifyCache.Add(s);
            }
            
        }

        private void rich_KeyDown(object sender, KeyEventArgs e)
        {

            //RichTextBox rich = (RichTextBox)sender;
            //string s = GetLastWord(rich.Text, rich.SelectionStart);
            ////跟据Index值，给不同关键字染色
            //if (AllClass()[s] != null)
            //{
            //    MySelect(rich, rich.SelectionStart, s, (Color)AllClass()[s], true);
            //}
            //else
            //{
            //    // 这里如果不解绑事件处理, 行号会出大问题
            //    rich.TextChanged -= new EventHandler(textBoxNode_TextChanged_1);
            //    MySelect(rich, rich.SelectionStart, s, Color.White, true);
            //    rich.TextChanged += new EventHandler(textBoxNode_TextChanged_1);
            //}
        }
        //建立python关键字列表
        public static Hashtable AllClass()
        {
            Hashtable ht = new Hashtable();
            // 红色
            Color color = Color.FromArgb(236, 96, 102);
            ht.Add("False", color);
            ht.Add("None", color);
            ht.Add("True", color);

            // Python关键字, 紫色
            color = Color.FromArgb(198, 149, 198);
            ht.Add("as", color);
            ht.Add("assert", color);
            ht.Add("break", color);
            ht.Add("class", color);
            ht.Add("continue", color);
            ht.Add("def", color);
            ht.Add("del", color);
            ht.Add("elif", color);
            ht.Add("else", color);
            ht.Add("finally", color);
            ht.Add("from", color);
            ht.Add("if", color);
            ht.Add("import", color);
            ht.Add("lambda", color);
            ht.Add("pass", color);
            ht.Add("raise", color);
            ht.Add("return", color);
            ht.Add("try", color);
            ht.Add("while", color);
            ht.Add("with", color);
            ht.Add("yield", color);
            ht.Add("for", color);

            // 其余保留字
            color = Color.FromArgb(249, 123, 87);
            ht.Add("in", color);
            ht.Add("is", color);
            ht.Add("not", color);
            ht.Add("or", color);
            ht.Add("and", color);
            return ht;
        }
        public static string GetLastWord(string str, int i)
        {
            string x = str;
            Regex reg = new Regex(@"[a-zA-Z]+$*", RegexOptions.RightToLeft);
            x = reg.Match(x).Value;
            Regex reg2 = new Regex(@"\s");
            x = reg2.Replace(x, "");
            return x;
        }

        //实现右键复制功能
        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxNode.Copy();
        }

        //实现右键剪切功能
        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxNode.Cut();
        }

        //实现右键粘贴功能
        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxNode.Paste();
        }

        //实现右键全选功能
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxNode.SelectAll();
        }

        //自动换行
        public void 自动换行_Click(object sender, EventArgs e)
        {
            textBoxNode.WordWrap = true;
        }


        //实现缩进功能
        private void textBoxNode_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter)
            //{

            //    //加入和上一行同样多的空格
            //    int start = textBoxNode.SelectionStart;
            //    int linenum = textBoxNode.GetLineFromCharIndex(start);
            //    if (textBoxNode.Lines.Length == 0)
            //    {
            //        return;
            //    }
            //    string line = textBoxNode.Lines[linenum].ToString();
            //    int blank_num = line.Length - line.TrimStart().Length;
            //    string autodadd = "\r\n";  //字符串，用于生成回车的效果
            //    for (int i = 0; i < blank_num; i++)
            //    {
            //        autodadd += ' ';  //循环增加空格
            //    }
            //    //如果上一行中有":"，则自动缩进
            //    if (line.EndsWith(":"))  //比较简单的一种判断方法
            //    {
            //        textBoxNode.Select(textBoxNode.GetFirstCharIndexFromLine(linenum), start - textBoxNode.GetFirstCharIndexFromLine(linenum));  //嘿嘿 这一句比较有意思
            //        if (textBoxNode.SelectedText.Trim() == "")
            //        {
            //            goto noauto;  //不缩进
            //        }
            //        autodadd += "    ";  //默认为缩进4个空格
            //    }
            //noauto:
            //    textBoxNode.SelectionStart = start;
            //    textBoxNode.SelectionLength = 0;
            //    textBoxNode.SelectedText = autodadd;
            //    textBoxNode.Refresh();
            //    e.Handled = true;  //结束事件
            //}

        }

        // 
        private void MySelect(RichTextBox tb, int i, string s, Color c, bool font)
        {
            if (i - s.Length+1 > 0) {
                tb.Select(i - s.Length, s.Length);
                tb.SelectionColor = c;
                //以下是把光标放到原来位置，并把光标后输入的文字重置
                tb.Select(i, 0);
                tb.SelectionColor = Color.White;
            }
            
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }


        // 全局扫描高亮
        public void scanAll()
        {
            Hashtable ht = AllClass();
            foreach (string str in ht.Keys)
            {
                Color color = (Color)ht[str];
                Regex regex = new Regex(@"\W" + str + @"\W");
                MatchCollection matchCollection = regex.Matches(textBoxNode.Text);
                foreach (Match match in matchCollection)
                {
                    textBoxNode.Select(match.Index + 1, str.Length);
                    textBoxNode.SelectionColor = color;
                }
            }
            string first = textBoxNode.Text.Split('\n')[0];
            foreach (string str in ht.Keys)
            {
                Color color = (Color)ht[str];
                Regex regex = new Regex(str + @"\W");
                MatchCollection matchCollection = regex.Matches(first);
                foreach (Match match in matchCollection)
                {
                    textBoxNode.Select(match.Index, str.Length);
                    textBoxNode.SelectionColor = color;
                }
            }
            // 高亮特殊符号
            QuoteLight("'");
            QuoteLight("\"");

            SingleLight("=", Color.FromArgb(249, 123, 87));
            SingleLight("/", Color.FromArgb(249, 123, 87));
            SingleLight(@"\+", Color.FromArgb(249, 123, 87));
            SingleLight(@"\*", Color.FromArgb(249, 123, 87));
            SingleLight("&", Color.FromArgb(249, 123, 87));
            SingleLight(@"\|", Color.FromArgb(249, 123, 87));
            SingleLight("-", Color.FromArgb(249, 123, 87));
            // 速度过慢, 暂时注释
            SingleLight(",", Color.FromArgb(166, 172, 185));
            SingleLight(@"\.", Color.FromArgb(166, 172, 185));
            SingleLight(":", Color.FromArgb(166, 172, 185));
            // 高亮函数调用
            FunctionLight();
            textBoxNode.Select(0, 0);
        }

        public void FunctionLight()
        {
            Color color = Color.FromArgb(98, 146, 193);
            Regex regex1 = new Regex(@"\(");
            MatchCollection matchCollection = regex1.Matches(textBoxNode.Text);
            foreach (Match match in matchCollection)
            {
                int length = 0;
                int index = match.Index;
                while (char.IsLetter(textBoxNode.Text[index - 1]) || textBoxNode.Text[index - 1] == '_')
                {
                    length++;
                    index--;
                    if (index == 0)
                    {
                        break;
                    }
                }
                textBoxNode.Select(match.Index - length, length);
                textBoxNode.SelectionColor = color;
            }
        }

        public void QuoteLight(string str)
        {
            // 单引号高亮
            Color color1 = Color.FromArgb(96, 180, 180);
            Regex regex1 = new Regex(str);
            MatchCollection matchCollection1 = regex1.Matches(textBoxNode.Text);
            for (int i = 0; i < matchCollection1.Count - 1; i = i + 2)
            {
                textBoxNode.Select(matchCollection1[i].Index, matchCollection1[i + 1].Index - matchCollection1[i].Index + 1);
                textBoxNode.SelectionColor = color1;
            }
        }

        public void SingleLight(string str, Color color)
        {
            Regex regex1 = new Regex(str);
            MatchCollection matchCollection1 = regex1.Matches(textBoxNode.Text);
            foreach (Match match in matchCollection1)
            {
                textBoxNode.Select(match.Index, 1);
                textBoxNode.SelectionColor = color;
            }
        }

        List<string> lastInput = new List<string>();
        public void textBoxNode_TextChanged_1(object sender, EventArgs e)
        {
            //if (nowKey == Keys.Space)
            //{
            //    return;
            //}
            //RichTextBox rich = (RichTextBox)sender;
            //// 普通高亮 
            ////string s = GetLastWord(rich.Text, rich.SelectionStart);
            //string s = inputCache;
            ////跟据Index值，给不同关键字染色
            //if (AllClass()[s] != null)
            //{
            //    MySelect(rich, rich.SelectionStart, s, (Color)AllClass()[s], true);
            //}
            //else
            //{
            //    // 这里如果不解绑事件处理, 行号会出大问题
            //    rich.TextChanged -= new EventHandler(textBoxNode_TextChanged_1);
            //    MySelect(rich, rich.SelectionStart, s, Color.White, true);
            //    rich.TextChanged += new EventHandler(textBoxNode_TextChanged_1);
            //}


            //int v = rich.SelectionStart;
            ////输入特殊符号时候的高亮
            //if (v >= 1)
            //{
            //    textBoxNode.Select(v - 1, 1);
            //}
            //string y = textBoxNode.SelectedText;
            //MessageBox.Show(textBoxNode.SelectionColor.ToString());
            //List<string> L = new List<string> { "=", "/", "+", "*", "-", "|", "*", "&", ":" };
            //if (L.Contains(y))
            //{
            //    textBoxNode.SelectionColor = Color.FromArgb(249, 123, 87);
            //}
            //MessageBox.Show(textBoxNode.SelectionColor.ToString());
            //textBoxNode.Select(v, 0);
            // 被逼无奈, 采用全局扫描
            int beforeScan = textBoxNode.SelectionStart;
            textBoxNode.Select(0, textBoxNode.Text.Length);
            textBoxNode.SelectionColor = Color.White;
            scanAll();
            textBoxNode.Select(beforeScan, 0);
        }

        // 获取字符串宽度
        public float GetFontWidth(string str, Font font)
        {
            Graphics graphics = CreateGraphics();
            SizeF sizeF = graphics.MeasureString(str, font);
            float returnValue = sizeF.Width;
            graphics.Dispose();
            return returnValue;
        }

        // 更新行号
        public void updateRowIndex()
        {
            //获取第一个可见字符的索引和行数
            Point pos = new Point(0, 0);
            int firstIndex = textBoxNode.GetCharIndexFromPosition(pos);
            int firstLine = textBoxNode.GetLineFromCharIndex(firstIndex);

            //获取最后一个可见字符的索引和最后一个可见行的数目
            pos.X += textBoxNode.ClientRectangle.Width;
            pos.Y += textBoxNode.ClientRectangle.Height;
            int lastIndex = textBoxNode.GetCharIndexFromPosition(pos);
            int lastLine = textBoxNode.GetLineFromCharIndex(lastIndex);

            pos = textBoxNode.GetPositionFromCharIndex(lastIndex);

            lineNumber.Text = "";
            if (isIndent)
            {
                for (int i = firstLine; i <= lastLine; i++)
                {
                    lineNumber.Text += i + 1 + "\r\n";
                }
                isIndent = false;
            }
            else
            {
                for (int i = firstLine; i <= lastLine + 1; i++)
                {
                    lineNumber.Text += i + 1 + "\r\n";
                }
            }


        }
        private void textBoxNode_VScroll_1(object sender, EventArgs e)
        {
            int p = textBoxNode.GetPositionFromCharIndex(0).Y % (textBoxNode.Font.Height + 1);
            lineNumber.Location = new Point(0, p);
            updateRowIndex();
        }

        Keys nowKey;
        bool isIndent = false;
        private void textBoxNode_KeyDown_1(object sender, KeyEventArgs e)
        {
            nowKey = e.KeyCode;
            if (e.KeyCode == Keys.Down && notifyBox.Visible == true)
            {
                notifyBox.Focus();
            }
            //实现缩进
            if (e.KeyCode == Keys.Enter)
            {
                //加入和上一行同样多的空格
                int start = textBoxNode.SelectionStart;
                if (textBoxNode.SelectionStart == 0) return;  //位于开始
                int linenum = textBoxNode.GetLineFromCharIndex(start);
                string line = textBoxNode.Lines[linenum].ToString();
                int blank_num = line.Length - line.TrimStart().Length;
                string autodadd = "\r\n";  //字符串，用于生成回车的效果

                for (int i = 0; i < blank_num; i++)
                {
                    autodadd += ' ';  //循环增加空格
                }
                if (line.EndsWith(":")) //比较简单的一种判断方法
                {
                    textBoxNode.Select(textBoxNode.GetFirstCharIndexFromLine(linenum), start - textBoxNode.GetFirstCharIndexFromLine(linenum));  //嘿嘿 这一句比较有意思
                    if (textBoxNode.SelectedText.Trim() == "")
                    {
                        goto noauto;  //不缩进
                    }
                    autodadd += "    ";  //默认为缩进4个空格

                }
            noauto:
                if (autodadd != "\r\n")
                {
                    isIndent = true;
                }
                textBoxNode.SelectionStart = start;
                textBoxNode.SelectionLength = 0;
                textBoxNode.SelectedText = autodadd;
                textBoxNode.Refresh();
                e.Handled = true;  //结束事件
            }
        }

        List<string> notifyCache = new List<string>();
        string inputCache = "";
        private void textBoxNode_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool isNotify = false;
            char value = e.KeyChar;
            // 增加行号
            // 如果是回车
            if (value == 13)
            {
                if (notifyBox.Visible && notifyBox.Height > 0)
                {
                    textBoxNode.Select(textBoxNode.Text.Length-inputCache.Length-1, inputCache.Length+1);
                    textBoxNode.SelectedText = notifyBox.SelectedItem.ToString();
                    lastInput.RemoveRange(lastInput.Count-inputCache.Length, inputCache.Length);
                    foreach (char s in notifyBox.SelectedItem.ToString().ToCharArray())
                    {
                        lastInput.Add(s.ToString());
                    }
                    notifyBox.Visible = false;

                    // 此次回车不被记录
                    isNotify = true;
                }
                else
                {
                    updateRowIndex();
                    inputCache = "";
                    SyncNotifyCache();
                }
                // 减少行号
            }
            // 如果是退格键
            else if (value == 8)
            {
                char Return = (char)13;
                if (lastInput != null && lastInput.Count != 0 && lastInput[lastInput.Count - 1] == Return.ToString())
                {
                    string[] tmp = lineNumber.Text.Split('\n');
                    tmp = tmp.Take(tmp.Length - 2).ToArray();
                    lineNumber.Text = string.Join("\n", tmp) + "\r\n";
                }
                // 关闭提示框
                notifyBox.Visible = false;
                inputCache = "";
                // 当输入的是字母, 开启补全
            }
            else if (char.IsLetter(value))
            {
                    inputCache += value.ToString();
                    notifyData.Clear();
                    BindingList<string> tmp = new BindingList<string>();
                    // 设置提示框的数据
                    foreach (string s in notifyCache)
                    {
                        if (s.Contains(inputCache))
                        {
                            tmp.Add(s);
                        }
                    }
                    // 按顺序排
                    foreach (string s in tmp)
                    {
                        if (s.StartsWith(inputCache))
                        {
                            notifyData.Add(s);
                        }
                    }
                    foreach (string s in tmp)
                    {
                        if (!notifyData.Contains(s))
                        {
                            notifyData.Add(s);
                        }
                    }


                    // 设置提示框尺寸和位置
                    notifyBox.Height = notifyData.Count > 5 ? 5 * textBoxNode.Font.Height : notifyData.Count * textBoxNode.Font.Height;
                    if (notifyBox.Height > 0)
                    {
                        Point location = textBoxNode.GetPositionFromCharIndex(textBoxNode.SelectionStart);
                        location.X = location.X + lineNumber.Width;
                        location.Y = location.Y + textBoxNode.Font.Height;
                        notifyBox.Location = location;
                        notifyBox.Visible = true;
                    }
                    else
                    {
                        notifyBox.Visible = false;
                    }
            }
            else
            {
                if (value == ' ')
                {
                    SyncNotifyCache();
                }
                notifyBox.Visible = false;
            }
            if (value != 8)
            {
                if (!isNotify)
                {
                    lastInput.Add(value.ToString());
                }
            }
            else
            {
                if (lastInput.Count > 0)
                {
                    lastInput.RemoveAt(lastInput.Count - 1);
                }
            }


            // char key = e.KeyChar;
            //MessageBox.Show(key.ToString());
            //for语句用来循环判断数组里有没有我们希望的值
            for (
                int i = 0; i < 2; i++)
            {
                if (e.KeyChar == eschar[i])
                {

                    //调用方法得到数据
                    LineColumn lc = Ranks();
                    //得到所在行第一个字符的索引
                    int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
                    //这个加不加都行
                    int number = index + lc.column;
                    //根据索引插入字符串
                    textBoxNode.Text = textBoxNode.Text.Insert(number, eschar[i].ToString());
                    //定位焦点
                    textBoxNode.Select(number, 0);

                }
            }
            //if语句用来判断
            if (e.KeyChar == '(')
            {
                LineColumn lc = Ranks();
                int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
                int number = index + lc.column;
                textBoxNode.Select(number, 0);
                textBoxNode.SelectedText += ")";
                textBoxNode.Select(number, 0);
            }
            else if (e.KeyChar == '{')
            {
                LineColumn lc = Ranks();
                int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
                int number = index + lc.column;
                textBoxNode.Select(number, 0);
                textBoxNode.SelectedText += "}";
                textBoxNode.Select(number-1, 0);
            }
            else if (e.KeyChar == '<')
            {
                LineColumn lc = Ranks();
                int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
                int number = index + lc.column;
                textBoxNode.Select(number, 0);
                textBoxNode.SelectedText += ">";
                textBoxNode.Select(number-1, 0);
            }
            else if (e.KeyChar == '[')
            {
                LineColumn lc = Ranks();
                int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
                int number = index + lc.column;
                textBoxNode.Select(number, 0);
                textBoxNode.SelectedText += "]";
                textBoxNode.Select(number-1, 0);
            }
        }

        private void notifyBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
            {
                textBoxNode.Select(textBoxNode.Text.Length - inputCache.Length - 1, inputCache.Length + 1);
                textBoxNode.SelectedText = notifyBox.SelectedItem.ToString();
                notifyBox.Visible = false;
                textBoxNode.Focus();
            }
        }

        public void SyncNotifyCache()
        {
            char[] separator = {' ', '\n', ',', '.', '(', ')'};
            string[] tmpList = textBoxNode.Text.Split(separator);
            foreach (string s in tmpList)
            {
                if (s.Length != 0)
                {
                    if (char.IsLetter(s.ToCharArray()[0]) && !notifyCache.Contains(s))
                    {
                        notifyCache.Add(s);
                    }
                }

            }
            inputCache = "";
        }

        public void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //textBoxNode.Undo();
            Stack before = new Stack();
            //入栈
            string str1 = this.textBoxNode.Text.ToString();
            char[] ctr = str1.ToCharArray();
            foreach (char c in ctr)
            {
                before.Push(c);
            }
            //出栈
            int i = before.Count;
            before.Pop();
            StringBuilder str2 = new StringBuilder();
            while (i > 1)
            {
                i--;
                str2.Append(before.Pop().ToString());
            }
            textBoxNode.Text = new string(str2.ToString().ToCharArray().Reverse().ToArray());
            //将光标移至最右边
            this.textBoxNode.SelectionStart = this.textBoxNode.Text.Length;
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void FormChild_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void FormChild_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        char[] eschar = { '"', '\'' };

        /// <summary>
        /// 实现自动补全括号功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public class LineColumn
        {
            public int line;
            public int column;
        };
        public LineColumn Ranks()
        {
            //得到光标行第一个字符的索引，即从第一个字符开始到光标行第一个字符的索引
            int index = textBoxNode.GetFirstCharIndexOfCurrentLine();
            //换算成光标行的行号，第一行开始计算，习惯第一行则加1
            int line = textBoxNode.GetLineFromCharIndex(index) + 1;
            //使用selectionstart得到光标所在位置的索引
            //这个索引减去当前行第一个字符的索引，由于光标的列数从0开始，所以加一
            int column = textBoxNode.SelectionStart - index;
            LineColumn lc = new LineColumn();
            lc.column = column;
            lc.line = line;
            return lc;
        }
        /// <summary>
        /// 键盘松开时 显示行号列号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxNode_KeyUp(object sender, KeyEventArgs e)
        {
            LineColumn lc = Ranks();
            toolStripStatusLabel1.Text = "第" + lc.line + "行";
            toolStripStatusLabel2.Text = "第" + lc.column + "列";
            int intLines = textBoxNode.GetLineFromCharIndex(textBoxNode.TextLength) + 1;
            toolStripStatusLabel3.Text = "共" + intLines + "行";
        }
        /// <summary>
        /// 鼠标点中后，显示行号列号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxNode_MouseUp(object sender, MouseEventArgs e)
        {
            LineColumn lc = Ranks();
            toolStripStatusLabel1.Text = "第" + lc.line + "行";
            toolStripStatusLabel2.Text = "第" + lc.column + "列";
            int intLines = textBoxNode.GetLineFromCharIndex(textBoxNode.TextLength) + 1;
            toolStripStatusLabel3.Text = "共" + intLines + "行";
        }

        private void textBoxNode_KeyUp_1(object sender, KeyEventArgs e)
        {

        }

        private void textBoxNode_MouseUp_1(object sender, MouseEventArgs e)
        {

        }
    }

    /// <summary>
    /// 用于取得一个文本文件的编码方式(Encoding)。
    /// </summary>
    internal class TxtFileEncoder
    {
        public TxtFileEncoder()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符，Encoding.Default将被返回。
        /// </summary>
        /// <param name="fileName">文件名。</param>
        /// <returns></returns>
        public static Encoding GetEncoding(string fileName)
        {
            return GetEncoding(fileName, Encoding.Default);
        }
        /// <summary>
        /// 取得一个文本文件流的编码方式。
        /// </summary>
        /// <param name="stream">文本文件流。</param>
        /// <returns></returns>
        public static Encoding GetEncoding(FileStream stream)
        {
            return GetEncoding(stream, Encoding.Default);
        }
        /// <summary>
        /// 取得一个文本文件的编码方式。
        /// </summary>
        /// <param name="fileName">文件名。</param>
        /// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时，将返回该编码方式。</param>
        /// <returns></returns>
        public static Encoding GetEncoding(string fileName, Encoding defaultEncoding)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open);
            Encoding targetEncoding = GetEncoding(fs, defaultEncoding);
            fs.Close();
            return targetEncoding;
        }
        /// <summary>
        /// 取得一个文本文件流的编码方式。
        /// </summary>
        /// <param name="stream">文本文件流。</param>
        /// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时，将返回该编码方式。</param>
        /// <returns></returns>
        public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding)
        {
            Encoding targetEncoding = defaultEncoding;
            if (stream != null && stream.Length >= 2)
            {
                //保存文件流的前4个字节
                byte byte1 = 0;
                byte byte2 = 0;
                byte byte3 = 0;
                byte byte4 = 0;
                //保存当前Seek位置
                long origPos = stream.Seek(0, SeekOrigin.Begin);
                stream.Seek(0, SeekOrigin.Begin);

                int nByte = stream.ReadByte();
                byte1 = Convert.ToByte(nByte);
                byte2 = Convert.ToByte(stream.ReadByte());
                if (stream.Length >= 3)
                {
                    byte3 = Convert.ToByte(stream.ReadByte());
                }
                if (stream.Length >= 4)
                {
                    byte4 = Convert.ToByte(stream.ReadByte());
                }
                //根据文件流的前4个字节判断Encoding
                //Unicode {0xFF, 0xFE};
                //BE-Unicode {0xFE, 0xFF};
                //UTF8 = {0xEF, 0xBB, 0xBF};
                if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
                {
                    targetEncoding = Encoding.BigEndianUnicode;
                }
                if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
                {
                    targetEncoding = Encoding.Unicode;
                }
                if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
                {
                    targetEncoding = Encoding.UTF8;
                }
                //恢复Seek位置
                stream.Seek(origPos, SeekOrigin.Begin);
            }
            return targetEncoding;
        }



        // 新增加一个方法，解决了不带BOM的 UTF8 编码问题

        /// <summary>
        /// 通过给定的文件流，判断文件的编码类型
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns>文件的编码类型</returns>
        public static System.Text.Encoding GetEncoding(Stream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            byte[] ss = r.ReadBytes(4);
            if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            else
            {
                if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
                {
                    reVal = Encoding.UTF8;
                }
                else
                {
                    int i;
                    int.TryParse(fs.Length.ToString(), out i);
                    ss = r.ReadBytes(i);

                    if (IsUTF8Bytes(ss))
                        reVal = Encoding.UTF8;
                }
            }
            r.Close();
            return reVal;

        }

        /// <summary>
        /// 判断是否是不带 BOM 的 UTF8 格式
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1;　 //计算当前正分析的字符应还有的字节数
            byte curByte; //当前分析的字节.
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式!");
            }
            return true;
        }


    }

}
